package com.cneport.das.client.trans.controller;

import com.cneport.das.client.trans.service.DasClientException;
import com.cneport.das.client.trans.service.TransClientService;
import com.cneport.das.common.model.trans.*;
import com.cneport.das.common.utils.BizRecorder;
import com.cneport.das.common.utils.JAXBUtils;
import com.cneport.das.common.utils.JsonUtil;
import com.cneport.das.common.validate.FieldCheckUtil;
import com.cneport.das.common.validate.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;
import java.util.Arrays;

/**
 * DAS Client
 *
 * @Author GavinZhang
 * @date 2021-12-20 16:43:54
 */
@RestController
@Slf4j
public class TransClientController {

    @Autowired
    BizRecorder bizRecorder;
    @Autowired
    TransClientService clientService;

    /**
     * 1 根据请求头调用工具类 转为对应的对象
     * 2 调用service处理
     *
     * @param httpRequest
     * @param requestBody
     */
    @PostMapping(path = "/putClientMsg")
    public String putMsg(HttpServletRequest httpRequest, @RequestBody String requestBody) {
        try {
            requestBody = URLDecoder.decode(requestBody, "UTF-8");
            if (requestBody.endsWith("=")) {
                requestBody = requestBody.substring(0, requestBody.length() - 1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        ErpPutRequest request = null;
        String guid = "";
        try {
            // 1 转换
            request = parseBean(httpRequest, requestBody, ErpPutRequest.class);
            guid = request.getReqHead().getGuid();
        } catch (Exception e) {
            e.printStackTrace();
            return JAXBUtils.obj2Xml(putFail(guid, "-1", "client 端处理失败！"));
        }

        //格式校验
        ResultVO validate = FieldCheckUtil.validate(request, null);
        if (!validate.isSuccess()) {
            return JAXBUtils.obj2Xml(putFail(guid, "-1", validate.getErrorStr()));
        }
        // 3 记录报文
        bizRecorder.write(request.getReqHead().getMsgType(), request.getReqHead().getGuid(), requestBody);
        // 4 调用服务端
        try {
            return clientService.putMsg(request);
        } catch (Exception e) {
            e.printStackTrace();
            return JAXBUtils.obj2Xml(putFail(guid, "-1", "client 端处理失败！"));
        }

    }

    @PostMapping(path = "/getClientMsg")
    @ResponseBody
    public String query(HttpServletRequest httpRequest, @RequestBody String requestBody) {

        ErpGetRequest dasGetReq = null;
        try {
            // 1 转换
            dasGetReq = parseBean(httpRequest, requestBody, ErpGetRequest.class);
        } catch (Exception e) {
            e.printStackTrace();
            return JAXBUtils.obj2Xml(getFail(dasGetReq.getReqHead().getGuid(), "-1", "client 处理失败！"));
        }
        //格式校验
        ResultVO validate = FieldCheckUtil.validate(dasGetReq, null);
        if (!validate.isSuccess()) {
            return JAXBUtils.obj2Xml(getFail(dasGetReq.getReqHead().getGuid(), "-1", validate.getErrorStr()));
        }

        // 3 记录报文
        bizRecorder.write("fetch", dasGetReq.getReqHead().getGuid(), requestBody);

        try {
            // 4 调用服务端
            return clientService.query(dasGetReq);
        } catch (Exception e) {
            e.printStackTrace();
            return JAXBUtils.obj2Xml(getFail(dasGetReq.getReqHead().getGuid(), "-1", "client 处理失败！"));
        }

    }

    private <T> T parseBean(HttpServletRequest httpRequest, String requestBody, Class<T> t) throws DasClientException {
        T req;
        try {

            if (MediaType.APPLICATION_JSON_VALUE.equals(httpRequest.getContentType())) {
                req = JsonUtil.toBean(requestBody, t);
            } else {
                req = JAXBUtils.xml2Obj(t, requestBody);
            }
            return req;
        } catch (Exception e) {
            throw new DasClientException("DAS 客户端接入数据格式转换失败！");
        }
    }

    private ErpPutResponse putFail(String guid, String errorCode, String msg) {
        ErpPutResponse erpPutResponse = new ErpPutResponse();
        erpPutResponse.setRespHead(ErpPutResponse.RespHead.builder().respCode(errorCode).respMsg(msg).reqGuid(guid).build());
        erpPutResponse.setAddInfos(new AddInfos(Arrays.asList(new AddInfos.AddInfo("", ""))));
        return erpPutResponse;
    }

    private ErpGetResponse getFail(String guid, String errorCode, String msg) {
        ErpGetResponse erpGetResponse = new ErpGetResponse();
        erpGetResponse.setRespHead(ErpGetResponse.RespHead.builder().respCode(errorCode).respMsg(msg).guid(guid).build());
        erpGetResponse.setAddInfos(new AddInfos(Arrays.asList(new AddInfos.AddInfo("", ""))));
        return erpGetResponse;
    }
}
